import React, { useState, useEffect, useRef } from 'react';
import Scene from './components/Scene';
import UnifiedControlPanel from './components/UnifiedControlPanel';
import WebGLFallback from './components/WebGLFallback';
import { FlightController } from './utils/FlightController';
import { FormationController } from './utils/FormationController';
import { detectWebGL, logWebGLInfo } from './utils/webglUtils';
import './App.css';

function App() {
  const [animationSpeed, setAnimationSpeed] = useState(1);
  const [showComponents, setShowComponents] = useState({
    frame: true,
    rotors: true,
    camera: true,
    landingGear: true,
    lights: true
  });
  const [colors, setColors] = useState({
    frame: '#2c3e50',
    rotors: '#34495e',
    camera: '#1a1a1a',
    lights: '#e74c3c'
  });
  // Removed environment state as we're using simple background color
  const [showGrid, setShowGrid] = useState(true);
  const [showStats, setShowStats] = useState(false);
  // Panel visibility states removed - now handled by unified control panel

  // Environment settings
  const [showObstacles, setShowObstacles] = useState(true);
  const [showBoundaries, setShowBoundaries] = useState(true);
  const [showTerrain, setShowTerrain] = useState(true);
  const [mapSize, setMapSize] = useState(50);
  const [showTrails, setShowTrails] = useState(false);

  // WebGL detection
  const [webglInfo, setWebglInfo] = useState(null);

  // Camera settings - optimized for better user experience
  const [cameraSettings, setCameraSettings] = useState({
    enablePan: true,
    enableZoom: true,
    enableRotate: true,
    minDistance: 2,
    maxDistance: 50,
    autoRotate: false,
    autoRotateSpeed: 0.3,
    panSpeed: 0.4,
    rotateSpeed: 0.4,
    zoomSpeed: 0.8,
    smoothness: 0.08,
    target: [0, 1, 0] // Focus slightly above ground level
  });

  // Flight controller and state
  const flightController = useRef(new FlightController());
  const [flightState, setFlightState] = useState(flightController.current.getState());

  // Formation controller and state
  const formationController = useRef(new FormationController());
  const [formationState, setFormationState] = useState(formationController.current.getFormationState());

  // WebGL detection on mount
  useEffect(() => {
    const webgl = detectWebGL();
    setWebglInfo(webgl);
    logWebGLInfo(webgl);
  }, []);

  // Update flight controller and formation controller
  useEffect(() => {
    const updateLoop = setInterval(() => {
      flightController.current.update(1/60); // 60 FPS
      const newFlightState = flightController.current.getState();
      setFlightState(newFlightState);

      // Update formation controller with main drone position
      formationController.current.updateMainDronePosition(
        newFlightState.position,
        newFlightState.rotation
      );
      formationController.current.update(1/60);
      setFormationState(formationController.current.getFormationState());
    }, 1000/60);

    return () => clearInterval(updateLoop);
  }, []);

  // Enhanced keyboard controls with arrow keys and WASD
  useEffect(() => {
    const handleKeyDown = (event) => {
      // Allow keyboard control even when not flying for easier testing
      const canControl = !flightState.autopilot;
      if (!canControl) return;

      // Prevent default behavior for navigation keys
      if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(event.code)) {
        event.preventDefault();
      }

      switch (event.code) {
        // WASD Controls
        case 'KeyW':
        case 'ArrowUp':
          flightController.current.setInput('forward', true);
          break;
        case 'KeyS':
        case 'ArrowDown':
          flightController.current.setInput('backward', true);
          break;
        case 'KeyA':
        case 'ArrowLeft':
          flightController.current.setInput('left', true);
          break;
        case 'KeyD':
        case 'ArrowRight':
          flightController.current.setInput('right', true);
          break;

        // Altitude Controls
        case 'Space':
        case 'KeyR':
          flightController.current.setInput('up', true);
          break;
        case 'ShiftLeft':
        case 'ShiftRight':
        case 'KeyF':
          flightController.current.setInput('down', true);
          break;

        // Rotation Controls
        case 'KeyQ':
          flightController.current.setInput('rotateLeft', true);
          break;
        case 'KeyE':
          flightController.current.setInput('rotateRight', true);
          break;

        // Quick Actions
        case 'KeyT':
          if (!flightState.isFlying) {
            flightController.current.takeOff();
          }
          break;
        case 'KeyL':
          if (flightState.isFlying) {
            flightController.current.land();
          }
          break;
        case 'Escape':
          flightController.current.emergencyStop();
          break;
      }
    };

    const handleKeyUp = (event) => {
      switch (event.code) {
        // WASD Controls
        case 'KeyW':
        case 'ArrowUp':
          flightController.current.setInput('forward', false);
          break;
        case 'KeyS':
        case 'ArrowDown':
          flightController.current.setInput('backward', false);
          break;
        case 'KeyA':
        case 'ArrowLeft':
          flightController.current.setInput('left', false);
          break;
        case 'KeyD':
        case 'ArrowRight':
          flightController.current.setInput('right', false);
          break;

        // Altitude Controls
        case 'Space':
        case 'KeyR':
          flightController.current.setInput('up', false);
          break;
        case 'ShiftLeft':
        case 'ShiftRight':
        case 'KeyF':
          flightController.current.setInput('down', false);
          break;

        // Rotation Controls
        case 'KeyQ':
          flightController.current.setInput('rotateLeft', false);
          break;
        case 'KeyE':
          flightController.current.setInput('rotateRight', false);
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, [flightState.autopilot]);

  // Mission handlers
  const handleMissionStart = (mission) => {
    flightController.current.startMission(mission);
  };

  const handleMissionStop = () => {
    flightController.current.completeMission();
  };

  const handleExport = (type) => {
    if (type === 'screenshot') {
      // Create a link to download the canvas as image
      const canvas = document.querySelector('canvas');
      if (canvas) {
        const link = document.createElement('a');
        link.download = 'drone-model.png';
        link.href = canvas.toDataURL();
        link.click();
      }
    } else if (type === 'gltf') {
      // For GLTF export, we'd need additional libraries
      alert('GLTF export feature coming soon! For now, you can take a screenshot.');
    }
  };

  // Show WebGL fallback if WebGL is not supported
  if (webglInfo && !webglInfo.supported) {
    return <WebGLFallback webglInfo={webglInfo} />;
  }

  // Show loading if WebGL detection is still in progress
  if (!webglInfo) {
    return (
      <div className="app">
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          color: 'white',
          fontSize: '1.2em',
          textAlign: 'center'
        }}>
          <div style={{ fontSize: '3em', marginBottom: '20px' }}>🚁</div>
          Initializing Drone System...
        </div>
      </div>
    );
  }

  return (
    <div className="app">
      <Scene
        animationSpeed={animationSpeed}
        showComponents={showComponents}
        colors={colors}
        showGrid={showGrid}
        showStats={showStats}
        flightState={flightState}
        formationState={formationState}
        showTrails={showTrails}
        showObstacles={showObstacles}
        showBoundaries={showBoundaries}
        showTerrain={showTerrain}
        mapSize={mapSize}
        cameraSettings={cameraSettings}
      />

      <UnifiedControlPanel
        animationSpeed={animationSpeed}
        setAnimationSpeed={setAnimationSpeed}
        showComponents={showComponents}
        setShowComponents={setShowComponents}
        colors={colors}
        setColors={setColors}
        showGrid={showGrid}
        setShowGrid={setShowGrid}
        showStats={showStats}
        setShowStats={setShowStats}
        onExport={handleExport}
        showTrails={showTrails}
        setShowTrails={setShowTrails}
        flightState={flightState}
        flightController={flightController.current}
        onMissionStart={handleMissionStart}
        onMissionStop={handleMissionStop}
        formationController={formationController.current}
        formationState={formationState}
        showObstacles={showObstacles}
        setShowObstacles={setShowObstacles}
        showBoundaries={showBoundaries}
        setShowBoundaries={setShowBoundaries}
        showTerrain={showTerrain}
        setShowTerrain={setShowTerrain}
        mapSize={mapSize}
        setMapSize={setMapSize}
        cameraSettings={cameraSettings}
        setCameraSettings={setCameraSettings}
      />
    </div>
  );
}

export default App;
